<template>
  <view class="my-total">
    <view class="one">
      <label class="radio">
        <radio @tap="radioChange(!isAll)" :checked="isAll" color="#c00000" /><text>全选</text>
      </label>
    </view>
    <view class="two">
      合计：<text>￥{{totalPrice}}</text>
    </view>
    <view class="three" @tap="payEvent">
      结算（{{total}}）
    </view>
  </view>
</template>

<script>
  import {
    mapGetters,
    mapState
  } from 'vuex'
  export default {
    name: "my-total",
    computed: {
      ...mapGetters('cart', ['total', 'totalPrice', 'isAll']),
      ...mapState('cart', ['cartList']),
      ...mapState('user', ['address', 'token'])
    },
    data() {
      return {

      };
    },
    methods: {
      radioChange(bool) {
        this.$store.commit('cart/setListStatus', bool)
      },
      // 结算
      async payEvent() {
        // 1:有地址
        if (!this.address) {
          return uni.showToast({
            title: '请先选择收货地址',
            icon: 'none'
          })
        }
        // 2：有需要支付的商品（商品数量>0）
        if (this.total === 0) {
          return uni.showToast({
            title: '请先选择需要购买的商品',
            icon: 'none'
          })
        }
        // 3:有token
        if (!this.token) {
          // uni.showToast({
          //   title: "请先登录",
          //   icon: 'none'
          // }) 
          // 倒计时提示
          return this.timeTip()
          // 存储回跳地址
          // 跳转到登录页
        }
        // 开始支付的处理
        // 1:产生订单
        const orderNumber = await this.createOrder()
        // 2:调用后端接口传入订单id获取支付时的参数
        const params = await this.getPayParams(orderNumber)
        // 3:调用微信支付api
        await uni.requestPayment({
          // provider: "微信小程序",
          ...params
        })
        // 支付完成
        uni.showToast({
          title: "支付完成"
        })
        // 清理已支付的购物车数据
        this.$store.commit('cart/clearPayList')
      },
      // 创建订单
      async createOrder() {
        const goods = this.cartList.filter(v => v.goods_status).map(item => {
          return {
            goods_id: item.goods_id,
            goods_number: item.goods_count,
            goods_price: item.goods_price
          }
        })
        const res = await uni.http({
          url: '/my/orders/create',
          method: 'post',
          // headers: {
          //   Authorization: this.token
          // },
          data: {
            order_price: this.totalPrice,
            consignee_addr: this.address.provinceName + this.address.cityName + this.address.countyName + this
              .address.detailInfo,
            goods
          }
        })
        return res.message.order_number
        console.log('订单编号 ', res);
      },
      // 获取支付参数
      async getPayParams(orderNumber) {
        const res = await uni.http({
          url: '/my/orders/req_unifiedorder',
          method: 'post',
          data: {
            order_number: orderNumber
          }
        })
        return res.message.pay
        console.log(res, '请求参数');
      },
      // 倒计时 3秒
      timeTip() {
        let n = 3
        uni.showToast({
          title: `${n}秒后跳转到登录页`,
          icon: 'none'
        })
        let timer = setInterval(() => {
          n--
          uni.showToast({
            title: `${n}秒后跳转到登录页`,
            icon: 'none'
          })
          if (n <= 0) {
            clearInterval(timer)
            uni.hideToast()
            // 获取当前路由地址
            const pages = getCurrentPages()
            this.$store.commit('user/setBackUrl', '/' + pages[pages.length - 1].route)
            uni.switchTab({
              url: "/pages/my/my"
            })
          }
        }, 1000)

      }
    }
  }
</script>

<style lang="scss" scoped>
  .my-total {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 100rpx;
    display: flex;
    align-items: center;
    background-color: #fff;
    z-index: 999;

    .one {
      flex: 2;
    }

    .two {
      flex: 3;

      text {
        color: #c00000;
      }
    }

    .three {
      flex: 2;
      height: 100rpx;
      background-color: #c00000;
      color: #fff;
      text-align: center;
      line-height: 100rpx;
    }
  }
</style>